package  
{
  import com.bit101.components.CheckBox;
  import com.bit101.components.PushButton;
  import flash.display.Sprite;
  import flash.events.Event;
  import flash.text.TextField;
  import flash.text.TextFieldType;
  import flash.text.TextFormat;
  import flash.events.TextEvent;
  import flash.events.KeyboardEvent;
  import flash.utils.Dictionary;
  import mge.StringUtils;
  
	/**
   * ...
   * @author ivan
   */
  public class TextEdit extends Sprite
  {
    private var buttons:Vector.<Array> = new Vector.<Array>();
    
    public function TextEdit() 
    {
      textField = new TextField();
      textField.width = 600;
      textField.height = 180;
      textField.y = 20;
      textField.multiline = true;
      textField.background = true;
      textField.type = TextFieldType.INPUT;
      textField.setTextFormat(new TextFormat("Verdana", 20));
      textField.text = "Text Code goes here";
      textField.selectable = true;
      textField.wordWrap = true;
      textField.addEventListener(TextEvent.TEXT_INPUT, onTextChange);
      textField.addEventListener(KeyboardEvent.KEY_UP, onTextChange);
      
      new CheckBox(this, 0, 0, "AutoFormat", onAutoFormatChange);
      
      buttons.push(new Array('p', '<p>', '</p>'));
      buttons.push(new Array('h1', '<h1>', '</h1>'));
      //buttons.push(new Array('b', '<b>', '</b>'));
      //buttons.push(new Array('i', '<i>', '</i>'));
      //buttons.push(new Array('u', '<u>', '</u>'));
      buttons.push(new Array('s1', '<span class="important">', '</span>'));
      buttons.push(new Array('s2','<span class="small">', '</span>'));
      
      var bd:Array;
      var xpos:int = 100;
      for each (bd in buttons)
      {
        var b:PushButton = new PushButton(this, xpos, 0, bd[0], onButtonPress);
        b.width = 20;
        xpos += 20;
      }
      
      addChild(textField);      
    }
    
    private var autoFormat:Boolean;
    private function onAutoFormatChange(e:Event):void
    {
      autoFormat = (e.target as CheckBox).selected;
    }
    
    private function onButtonPress(e:Event):void
    {
      var begin:int = textField.selectionBeginIndex;
      var btnIdx:int = getBtnIdx((e.target as PushButton).label);
      var selectionEnd:int = textField.selectionEndIndex + buttons[btnIdx][1].length;
      textField.text = StringUtils.insert(textField.text, buttons[btnIdx][2], textField.selectionEndIndex);
      textField.text = StringUtils.insert(textField.text, buttons[btnIdx][1], begin);
      
      textField.dispatchEvent(new Event(TextEvent.TEXT_INPUT));
      
      textField.setSelection(selectionEnd, selectionEnd);
      stage.focus = textField;
    }
    
    private function getBtnIdx(text:String):int
    {
      for (var i:int = 0; i < buttons.length; i++)
        if (buttons[i][0] == text) return i;
      return -1;
    }
    
    public function set text(val:String):void
    {
      textField.text = val;
    }
    
    public function get text():String
    {
      return textField.text;
    }
    
    private function onTextChange(e:Event):void
    {
      if (!autoFormat) return;
      
      var text:String = textField.text;
      
      // Makes paragraphs based on end line characters.
      var idx:int = text.indexOf("\r");
      while (idx != -1)
      {
        text = text.replace("\r", " </p>");
        var startParagIdx:int = text.lastIndexOf("<p>", idx);
        var endParagIdx:int = text.lastIndexOf("</p>", idx);
        if (endParagIdx != -1)
        {
          text = StringUtils.insert(text, "<p>", endParagIdx + 4);
        }
        else if (startParagIdx != -1)
        {
          // Tag is already opened and properly closed
        }
        else
        {
          // Inserts at the beginning.
          text = StringUtils.insert(text, "<p>", 0);
        }
        idx = text.indexOf("\r", idx);
      }
      
      // Check last sentence is in a paragraph
      idx = text.lastIndexOf("</p>");
      if (idx == -1)
      {
        // The whole text is a paragraph
        text = "<p>" + text + " </p>";
      }
      else
      {
        if (idx < text.length - 4)
        {
          // Should open a paragraph right after last one.
          text = StringUtils.insert(text, "<p>", idx + 4);
          text += " </p>";
        }
        else
        {
          // last paragraph found is ok.
        }
      }
      
      if (text != textField.text)
      {
        textField.text = text;
        textField.setSelection(idx+4, idx+4);
      }
      else
      {
        textField.text = text;
      }
    }
    
    private var textField:TextField;
  }

}